# -*-coding:gbk-*-
# ProjectName: smart-meter-iot-test-console
# FileName: reportTask.py
# @DateTime :2023/3/20 11:04
# @Author :
# @Description:��ʱ�ϱ�����
import time
from time import sleep

from common.util.configUtil.configUtil import ConfigUtil
from common.util.jsonUtl.jsonUtil import JsonUtil
from common.util.logUtil.logUtil import LoggerUtil
from common.util.mySqlUtil.mySqlPool import select_sql
from common.util.timeUtil.timeUtil import get_now_time, get_timestamp
from core.mqtt.connect.mqtt import mqtt_connect, on_publish
from core.mqtt.libProject.reportData.reportData import packge_report_data_body, packge_reprt_collector_body

read_json = JsonUtil()
config = ConfigUtil()
deviceName = config.get_mqtt_config("deviceName")
productKey = config.get_productkey()
timestamp = get_timestamp()
client = mqtt_connect(deviceName)
logger = LoggerUtil()


def report() -> None:
    """
    :return:
    """
    try:
        client.loop_start()
        sleep(1)
        log_record()
        select_dbNoAndzhyg = read_json.read_sql("select_dbNoAndzhyg")
        db_data_list = select_sql(select_dbNoAndzhyg)
        count = 1
        for i in db_data_list:
            reporData = packge_report_data_body(i[0], i[1], i[2], i[3], i[4], i[5])
            topic = f"/{config.get_productkey()}/{deviceName}/user/update"
            on_publish(client, topic, str(reporData), 0)
            if count % 15 == 0:
                print(f"����:{count}")
                logger.debug(f"����:{count}")
                sleep(1)
            logger.info(f"�ϱ�����:\n{str(reporData)}")
            count += 1
        log_record(2)
    except Exception as e:
        logger.error(f"report: {e}")


def log_record(status: int = 1):
    if status == 1:
        startContent = "��ʼ"
    else:
        startContent = "����"
    print(f"�ϱ�{startContent}ʱ��:{get_now_time(1)}")
    logger.info(f"�ϱ�{startContent}ʱ��:{get_now_time(1)}")
    logger.debug(f"�ϱ�{startContent}ʱ��:{get_now_time(1)}")


def report_collector() -> None:
    """
    :return:
    """
    try:
        client.loop_start()
        log_record()
        topic = f"/{config.get_productkey()}/{deviceName}/user/update"
        on_publish(client, topic, str(packge_reprt_collector_body(deviceName)), 0)
        log_record(2)
    except Exception as e:
        logger.error(f"report: {e}")


if __name__ == '__main__':
    report()
    # report_collector()
